//
//  CityDetailViewController.m
//  BeautyClother
//
//  Created by dllo on 15/9/1.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "CityDetailViewController.h"
#import "define.h"
#import "UIImageView+WebCache.h"
#import "ImageSaveViewController.h"
#import "AsyncConnection.h"

@interface CityDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UIWebViewDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSDictionary *dic;
@property (nonatomic, retain) UIScrollView *scroll;
@property (nonatomic, retain) UIActivityIndicatorView *activity;
@property (nonatomic, retain) UIWebView *web;

@property (nonatomic, assign) CGFloat offWidth;
@property (nonatomic, assign) CGFloat offHeight;
@end

@implementation CityDetailViewController

- (void)dealloc
{
    [_array release];
    [_dic release];
    [_table release];
    [_scroll release];
    [_activity release];
    [_web release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
        self.offHeight = [[UIScreen mainScreen]bounds].size.height / 667;
        
    }
    return self;
}

// http://open.qyer.com/qyer/footprint/city_detail?city_id=11186&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.8826887350744&lon=121.5392263350393&page=1&track_app_channel=App%2520Store&track_app_version=6.6&track_device_info=iPhone%25205s&track_deviceid=2CC19978-A0E5-49F2-9719-59DC5EDE6BBB&track_os=ios%25208.4&v=1

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self beginConnection];
    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    self.title = @"城市简介";
    // Do any additional setup after loading the view.
}

- (void)beginConnection
{
    
    
    NSDictionary *dic = @{@"lat":@"38.8826887350744",
                          @"lon":@"121.5392263350393",
                          @"city_id":self.cityId,
                          @"page":@"1",
                          @"v":@"1",
                          @"count":@"20",
                          @"client_id":@"qyer_ios",
                          @"client_secret":@"cd254439208ab658ddf9",
                          @"track_os":@"ios%25208.4",
                          @"track_deviceid":@"2CC19978-A0E5-49F2-9719-59DC5EDE6BBB",
                          @"track_device_info":@"iPhone%25205s",
                          @"track_app_version":@"6.6"
                          };
    [AsyncConnection asyncConnection:CITY_DETAIL parmaters:dic block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.dic = [dic objectForKey:@"data"];
        NSArray *arr = [self.dic objectForKey:@"photos"];
        [self.array addObject:[arr lastObject]];
        [self.array addObjectsFromArray:arr];
        [self.array addObject:[arr firstObject]];
        
        [self createTableView];
    }path:self.cityId];
}


- (void)back:(id)button
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createTableView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.table ];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.table release];
    [self createScroll];
    [self createWebView];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
    }
    if (indexPath.section == 1) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
            
        }
        return cell;
    }else
    {
        return [[[UITableViewCell alloc]init]autorelease];
    }
}

- (void)createScroll
{
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250 *_offHeight)];
    
    _scroll.delegate = self;
    [self.table addSubview:self.scroll];
    _scroll.contentSize = CGSizeMake(self.array.count * _scroll.frame.size.width, 0);
    _scroll.pagingEnabled = YES;
    _scroll.contentOffset = CGPointMake(self.scroll.frame.size.width, 0);
    [self createImage];
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(20 * _offWidth, 100 *_offHeight, 200 *_offWidth, 50 *_offHeight)];
    [self.table addSubview:name];
    name.textColor = [UIColor whiteColor];
    name.font = [UIFont boldSystemFontOfSize:30];
    name.text = [self.dic objectForKey:@"cnname"];
    [name release];
    UILabel *engname = [[UILabel alloc]initWithFrame:CGRectMake(20 *_offWidth, 150 *_offHeight, 100 *_offWidth, 50 *_offHeight)];
    [self.table addSubview:engname];
    engname.textColor = [UIColor whiteColor];
    engname.text = [self.dic objectForKey:@"enname"];
    [engname release];
    UILabel *language = [[UILabel alloc]initWithFrame:CGRectMake(20 *_offWidth, 200 *_offHeight, 300 *_offWidth, 50 *_offHeight)];
    [self.table addSubview:language];
    language.textColor = [UIColor whiteColor];
    language.numberOfLines = 2;
    language.font = [UIFont systemFontOfSize:15];
    language.text = [self.dic objectForKey:@"entryCont"];
    [language release];
    [_scroll release];
    
    
}

- (void)timerAction:(NSTimer *)timer
{
    
    if (_scroll.contentOffset.x == self.view.frame.size.width * (self.array.count - 2) ) {
        
        _scroll.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    }else
    {
        
        _scroll.contentOffset = CGPointMake(_scroll.contentOffset.x + self.view.frame.size.width, 0);
    }
}


- (void)createImage
{
    for (int i = 0; i < self.array.count; i++) {
        UIImageView *iamge = [[UIImageView alloc]initWithFrame:CGRectMake(i * self.view.frame.size.width, 0, self.view.frame.size.width, self.scroll.frame.size.height)];
        
        [self.scroll addSubview:iamge];
        [iamge sd_setImageWithURL:[NSURL URLWithString:[self.array objectAtIndex:i]] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
        
        [iamge release];
    }
    
}

- (void)createWebView
{
    self.web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 250 *_offHeight, self.view.frame.size.width, self.view.frame.size.height - 200 *_offHeight)];
    [self.table addSubview:_web];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[self.dic objectForKey:@"overview_url"]]];
    _web.delegate = self;
    _web.scrollView.delegate = self;
    [_web loadRequest:request];
    
    [_web release];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 250 *_offHeight, self.view.frame.size.width, self.view.frame.size.height - 200 *_offHeight)];
    [self.table addSubview:view];
    view.tag = 100;
    view.backgroundColor = [UIColor blackColor];
    [view release];
    
    
    self.activity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(10 *_offWidth, 100 *_offHeight, 200 *_offWidth, 200 *_offHeight)];
    [self.activity setCenter:CGPointMake(self.view.frame.size.width / 2, 100)];
    [self.activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    
    [view addSubview:self.activity];
    [self.activity startAnimating];
    
    [self.activity release];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.activity stopAnimating];
    [[self.view viewWithTag:100]removeFromSuperview];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 250 *_offHeight ;

    }else{
        
        return self.view.frame.size.height - 200 *_offHeight;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.scroll) {
        if (scrollView.contentOffset.x == self.scroll.frame.size.width * (self.array.count - 1)) {
            
            scrollView.contentOffset = CGPointMake(self.scroll.frame.size.width, 0);
        }
        if (scrollView.contentOffset.x == 0) {
            scrollView.contentOffset = CGPointMake(self.scroll.frame.size.width * (self.array.count - 2), 0);
        }
    }
    
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.web.scrollView) {
        if (scrollView.contentOffset.y < 250 *_offHeight) {
            self.table.contentOffset = self.web.scrollView.contentOffset;
        }else
        {
            
            self.table.contentOffset = CGPointMake(0, 200 *_offHeight);
        }
    }
    if (scrollView == self.table) {
        if (scrollView.contentOffset.y > self.table.frame.size.height) {
            
        }
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
